<template>
  <div class="PageFoodContent">
    <div class="foodContent">
      <div class="foodCategory" ref="foodCategory">
        <ul>
          <li
            v-for="(category, i) in categories"
            :key="i"
            :class="{actived: i == activedIndex}"
            @click="focusCategory(i)"
          >
            <img v-if="category.icon_url" :src="getImgPath(category.icon_url)">
            <span>{{category.name}}</span>
            <i class="cornerNum" v-if="categoryNum[category.id]">{{categoryNum[category.id]}}</i>
          </li>
        </ul>
      </div>
      <div class="foodList" ref="foodList">
        <ul>
          <li v-for="(category,i) in categories" :key="i">
            <div class="groupHeader">
              <div class="categroyTitle">{{category.name}}</div>
              <div class="categroyDescription">{{category.description}}</div>
            </div>
            <div class="groupList">
              <div class="foodItem" v-for="(food, i) in category.foods" :key="i">
                <div class="foodDetail" :to="{path:'shop/foodDetail'}">
                  <div class="foodImg">
                    <img :src="imgBaseUrl + food.image_path">
                  </div>
                  <div class="foodInfo">
                    <h4 class="foodName ellipsis">{{food.name}}</h4>
                    <p class="foodDescription">{{food.description}}</p>
                    <p class="foodRating">
                      <span>月售{{food.month_sales}}份</span>
                      <span>好评率{{food.satisfy_rate}}%</span>
                    </p>
                    <p v-if="food.activity" class="foodActivity">
                      <span
                        :style="{color: '#' + food.activity.image_text_color, borderColor:'#' +food.activity.icon_color}"
                      >{{food.activity.image_text}}</span>
                    </p>
                    <div class="foodOrder" @click.stop>
                      <div class="foodPrice">
                        <span>¥</span>
                        <span>{{food.specfoods[0].price}}</span>
                        <span v-if="food.specifications.length">起</span>
                      </div>
                      <PageCartAdd
                        :food="food"
                        :order="orders[shopId] ? orders[shopId][food.item_id] : emptyMap"
                        :cartEvents="cartEvents"
                      />
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </li>
        </ul>
      </div>
    </div>
    <PageCart :cartProps="cartProps" :cartEvents="cartEvents"/>
    <PageSpecsWindow
      v-if="specsWindowProps.skus"
      :args="specsWindowProps"
      :order="orders[shopId] ? orders[shopId][specsWindowProps.skus[0].foodId] : emptyMap"
      :cartEvents="cartEvents"
    />
  </div>
</template>

<script>
import { mapState, mapActions } from 'vuex';
import { getImgPath } from '../../../etc/methods';
import { imgBaseUrl } from '../../../etc/config';
import PageCartAdd from './PageCartAdd';
import PageCart from './PageCart';
import PageSpecsWindow from './PageSpecsWindow';
import BScroll from 'better-scroll';
export default {
  data() {
    return {
      imgBaseUrl,

      emptyMap: {},
      orderTest: {},
      cartEvents: {
        // 购物车操作
        showSpecsWindow: foodId => {
          this.showSpecsWindow(foodId);
        },
        add: (foodId, skuId) => {
          this.cartAdd({ shopId: this.shopId, foodId, skuId });
        },
        reduce: (foodId, skuId) => {
          this.cartReduce({ shopId: this.shopId, foodId, skuId });
        }
      },

      cartProps: {
        totalPrice: 0,
        totalNum: 0,
        deliveryFee: this.shop.deliveryFee,
        shortOrderFee: 20,
        cartFoodList: [],
        shopId: this.shop.id
      },

      specsWindowProps: {
        skus: null,
        close: () => {
          this.closeSpecsWindow();
        }
      },

      activedIndex: 0,
      skuMetas: null, // 商品sku信息
      foodMetas: null,

      foodListTops: null,
      foodListScroll: null,
      scrollIsLock: false
    };
  },
  props: ['shop', 'shopId', 'categories'],
  created() {
    this.initOrders();
    this.initFoodMetas();
  },
  mounted() {
    this.initScroll();
  },
  watch: {
    orders() {
      if (!this.skuMetas) {
        return;
      }
      this.refreshCart();
    }
  },
  computed: {
    ...mapState(['orders']),
    shopOrders() {
      return this.orders[this.shopId] || {};
    },
    categoryNum() {
      let categoryOrders = {};
      let shopOrders = this.shopOrders;
      for (let foodId in shopOrders) {
        let foodOrders = shopOrders[foodId];
        for (let skuId in foodOrders) {
          let categoryId = this.foodMetas[foodId].categoryId;
          let prevNum = categoryOrders[categoryId] || 0;
          let skuNum = foodOrders[skuId];
          categoryOrders[categoryId] = prevNum + skuNum;
        }
      }
      return categoryOrders;
    }
  },
  methods: {
    getImgPath,
    ...mapActions(['cartAdd', 'cartReduce', 'initOrders']),

    initFoodMetas() {
      let skuMetas = {};
      let foodMetas = {};
      this.categories.forEach(category => {
        category.foods.forEach(food => {
          let foodSkus = [];
          foodMetas[food.item_id] = {
            categoryId: category.id,
            skus: foodSkus,
            foodId: food.item_id,
            foodName: food.name
          };
          food.specfoods.forEach(sku => {
            foodSkus.push({
              foodId: food.item_id,
              foodName: food.name,
              skuId: sku.sku_id,
              skuName: food.specfoods.length === 1 ? '' : sku.specs_name,
              skuPrice: sku.price
            });

            skuMetas[sku.sku_id] = {
              foodId: food.item_id,
              foodName: food.name,
              skuId: sku.sku_id,
              skuName: food.specfoods.length === 1 ? '' : sku.specs_name,
              price: sku.price
            };
          });
        });
      });
      this.skuMetas = skuMetas;
      this.foodMetas = foodMetas;
    },
    initScroll() {
      setTimeout(() => {
        let { foodCategory, foodList } = this.$refs;

        const foodCategoryScroll = new BScroll(foodCategory, {
          click: true
        });
        this.foodListScroll = new BScroll(foodList, {
          probeType: 3,
          deceleration: 0.001,
          bounce: false,
          swipeTime: 2000,
          click: true
        });

        const foodListTops = (this.foodListTops = Array.from(
          foodList.children[0].children
        ).map(item => item.offsetTop));
        const foodCategoryHeight = foodCategory.clientHeight;
        this.foodListScroll.on('scroll', pos => {
          // 同步调整类目表位置
          if (this.scrollIsLock) {
            // 类目在滚动的时候，停止同步调整
            return;
          }
          let offsetTop = Math.abs(Math.round(pos.y));
          let targetIndex = null;
          for (let i = 0; i < foodListTops.length; i++) {
            if (offsetTop >= foodListTops[i]) {
              targetIndex = i;
            }
          }

          if (targetIndex != null && targetIndex !== this.activedIndex) {
            //console.info('targetIndex', targetIndex);
            this.activedIndex = targetIndex;
            foodCategoryScroll.scrollToElement(
              foodCategory.children[0].children[targetIndex],
              800,
              0,
              -(foodCategoryHeight / 2 - 50)
            );
          }
        });

        this.foodListScroll.on('scrollEnd', () => {
          this.scrollIsLock = false;
        });

        // console.info(this.foodGroupList);
      });
    },
    focusCategory(index) {
      if (this.activedIndex !== index) {
        this.activedIndex = index;
        this.scrollIsLock = true;
        this.foodListScroll.scrollTo(0, -this.foodListTops[index], 400);
      }
    },
    refreshCart() {
      let shopOrders = this.shopOrders;
      let skuMetas = this.skuMetas;
      let totalNum = 0;
      let totalPrice = 0;
      let cartFoodList = [];
      for (let foodId in shopOrders) {
        let foodOrders = shopOrders[foodId];
        for (let skuId in foodOrders) {
          let sku = skuMetas[skuId];
          let foodPrice = sku.price * foodOrders[skuId];
          totalNum += foodOrders[skuId];
          totalPrice += foodPrice;
          cartFoodList.push({
            name: sku.foodName,
            specs: sku.skuName,
            num: foodOrders[skuId],
            price: foodPrice,
            skuId: sku.skuId,
            foodId: sku.foodId
          });
        }
      }

      this.cartProps = {
        ...this.cartProps,
        totalNum,
        totalPrice,
        cartFoodList,
        shortOrderFee: Math.max(0, this.shop.minOrderFee - totalPrice)
      };
    },
    showSpecsWindow(foodId) {
      this.specsWindowProps.skus = this.foodMetas[foodId].skus;
    },
    closeSpecsWindow() {
      this.specsWindowProps.skus = null;
    }
  },
  components: {
    PageCartAdd,
    PageCart,
    PageSpecsWindow
  }
};
</script>

<style lang="scss">
@import '../../../styles/mixin';
.PageFoodContent {
  display: flex;
  flex: 1;
  padding-bottom: 2rem;

  .foodContent {
    display: flex;
    flex: 1;
    overflow-y: hidden;
    position: relative;

    .foodCategory {
      width: 3.7rem;
      overflow-y: auto;
      li {
        padding: 0.7rem 0.3rem;
        border-bottom: 0.025rem solid #ededed;
        box-sizing: border-box;
        border-left: 0.15rem solid #f8f8f8;
        position: relative;
        img {
          @include wh(0.5rem, 0.6rem);
        }
        span {
          @include sc(0.6rem, #666);
        }
        .order-num {
          position: absolute;
          top: 0.1rem;
          right: 0.1rem;
          background-color: #ff461d;
          line-height: 0.6rem;
          text-align: center;
          border-radius: 50%;
          border: 0.025rem solid #ff461d;
          min-width: 0.6rem;
          height: 0.6rem;
          @include sc(0.5rem, #fff);
          font-family: Helvetica Neue, Tahoma, Arial;
        }
      }

      li.actived {
        border-left: 0.15rem solid #3190e8;
        background-color: #fff;
        span:nth-of-type(1) {
          font-weight: bold;
        }
      }

      .cornerNum {
        top: 0;
        right: 0;
        line-height: 0.8rem;
        min-width: 0.8rem;
        height: 0.8rem;
        border-radius: 0.4rem;
      }
    }
    .foodList {
      flex: 4;
      overflow-y: auto;
      .groupHeader {
        width: 100%;
        padding: 0.4rem;
        position: relative;
        display: flex;
        align-items: baseline;
        .categroyTitle {
          font-size: 0.7rem;
          color: #666;
          font-weight: 700;
        }
        .categroyDescription {
          font-size: 0.5rem;
          color: #999;
          width: 50%;
          margin-left: 0.3rem;
        }
      }
      .foodItem {
        background-color: #fff;
        padding: 0.6rem 0.4rem;
        border-bottom: 1px solid #f8f8f8;
        position: relative;
        overflow: hidden;

        .foodDetail {
          display: flex;
        }
        .foodImg {
          margin-right: 0.3rem;
          img {
            display: block;
            width: 2rem;
            height: 2rem;
          }
        }
        .foodInfo {
          flex: 1;
          .foodName {
            font-size: 0.7rem;
            color: #333;
            width: 8rem;
          }
          .foodDescription {
            font-size: 0.5rem;
            color: #999;
            line-height: 0.6rem;
          }
          .foodRating {
            color: #333;
            font-size: 0.5rem;
          }
          .foodActivity {
            span {
              font-size: 0.5rem;
              border: 1px solid currentColor;
              border-radius: 0.2rem;
              padding: 0.06rem 0.2rem;
              display: inline-block;
              transform: scale(0.8);
            }
          }

          .foodOrder {
            display: flex;
            justify-content: space-between;
            font-size: 0;
            margin-top: 0.2rem;
            .foodPrice {
              span {
                font-family: 'Helvetica Neue', Tahoma, Arial;
              }
              span:nth-of-type(1) {
                @include sc(0.5rem, #f60);
                margin-right: 0.05rem;
              }
              span:nth-of-type(2) {
                @include sc(0.7rem, #f60);
                font-weight: bold;
                margin-right: 0.3rem;
              }
              span:nth-of-type(3) {
                @include sc(0.5rem, #666);
              }
            }
          }
        }
      }
    }
  }
}
</style>